/**
 * 
 */
package com.yunyike.controller.order;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yunyike.constants.CommonConstant;
import com.yunyike.constants.RequestConstant;
import com.yunyike.constants.ResponseConstant;
import com.yunyike.controller.BaseController;
import com.yunyike.dto.OrderDTO;
import com.yunyike.dto.cart.CartDTO;
import com.yunyike.model.Coupon;
import com.yunyike.model.Orders;
import com.yunyike.model.Recepient;
import com.yunyike.model.User;
import com.yunyike.response.Response;
import com.yunyike.service.ICartService;
import com.yunyike.service.ICouponService;
import com.yunyike.service.IOrderService;
import com.yunyike.service.IRecepientService;
import com.yunyike.utils.CookieUtils;
import com.yunyike.utils.JsonUtils;
import com.yunyike.utils.LocationUtils;
import com.yunyike.utils.UserUtils;
import com.yunyike.vo.OrderVO;

/**
 * @author zhengqiang.shi
 * 2015年11月18日 下午8:53:31
 */
@Controller
@RequestMapping(value=RequestConstant.ORDER)
public class OrderController extends BaseController {

	private Logger log = LoggerFactory.getLogger(OrderController.class);
	
	@Autowired
	private IOrderService orderService;
	
	@Autowired
	private ICouponService couponService;
	
	@Autowired
	private IRecepientService recepientService;
	
	@Autowired
	private ICartService cartService;
	
	@Autowired
	private LocationUtils locationUtils;
	
	@Value("${openids}")
	private String openids;
	
	@ResponseBody
	@RequestMapping(value=RequestConstant.ORDER_SUBMIT)
	public void submit(@Validated OrderVO orderVO,BindingResult br,
			HttpServletResponse response){
		
		Response res = new Response();
		
		// 请求参数检查
		checkRequest(br, res, response);
		
		// 当前用户
		User user = getCurrentUser();
		
		// 收货地址
		Recepient recepient = recepientService.findByIdAndUserId(orderVO.getAddressId(), user.getUserId());
		if(recepient == null){
			res.getResult().setCode(CommonConstant.NUMBER__6);
			res.getResult().setMessage(ResponseConstant.submitOrderMessage.get(CommonConstant.NUMBER__6));
			returnDatas(res, response);
			return;
		}
		
		// 优惠券
		String couponId = orderVO.getCouponId();
		Coupon useCoupon = null;
		if(StringUtils.isNotBlank(couponId)){
			Coupon coupon = new Coupon();
			coupon.setUserId(user.getUserId());
			coupon.setCouponId(couponId);
			List<Coupon> list = couponService.findCouponByCondition(coupon);
			if(list == null || list.isEmpty()){
				res.getResult().setCode(CommonConstant.NUMBER__7);
				res.getResult().setMessage(ResponseConstant.submitOrderMessage.get(CommonConstant.NUMBER__7));
				returnDatas(res, response);
				return;
			}
			useCoupon = list.get(0);
			
			Integer couponStatus = useCoupon.getCouponStatus();
			if(couponStatus != CommonConstant.NUMBER_0){
				log.info("couponStatus not is 0");
				res.getResult().setCode(CommonConstant.NUMBER__7);
				res.getResult().setMessage(ResponseConstant.submitOrderMessage.get(CommonConstant.NUMBER__7));
				returnDatas(res, response);
				return;
			}
			
			Date couponStartDate = useCoupon.getCouponStartDate();
			Date couponEndDate = useCoupon.getCouponEndDate();
			Date date = new Date();
			// 优惠券在有效期范围内
			if(date.compareTo(couponStartDate) != 1 || date.compareTo(couponEndDate) != -1){
				log.info("Coupon is not valid");
				res.getResult().setCode(CommonConstant.NUMBER__7);
				res.getResult().setMessage(ResponseConstant.submitOrderMessage.get(CommonConstant.NUMBER__7));
				returnDatas(res, response);
				return;
			}
			
		}
		
		// 购物车信息
		String[] merchandiseId = orderVO.getMerchandiseId();
		CartDTO cartDTO = cartService.settlement(user, Arrays.asList(merchandiseId));
		if(cartDTO == null){
			res.getResult().setCode(CommonConstant.NUMBER__8);
			res.getResult().setMessage(ResponseConstant.submitOrderMessage.get(CommonConstant.NUMBER__8));
			returnDatas(res, response);
			return;
		}
		
		if(useCoupon != null){
			BigDecimal totalMerchandisePrice = cartDTO.getTotalMerchandisePrice();
			Double couponUsePrice = useCoupon.getCouponUsePrice();
			if(totalMerchandisePrice.compareTo(new BigDecimal(couponUsePrice)) != 1){
				log.info("Coupons are not allowed to use");
				res.getResult().setCode(CommonConstant.NUMBER__7);
				res.getResult().setMessage(ResponseConstant.submitOrderMessage.get(CommonConstant.NUMBER__7));
				returnDatas(res, response);
				return;
			}
		}
		
		Orders orders = orderService.submitOrder(user, recepient, useCoupon, cartDTO);
		
		res.setData(orders);
		returnDatas(res, response);
	}
	
	/**
	 * 提交订单
	 * @throws IOException 
	 */
	//@ResponseBody
	//@RequestMapping(value=RequestConstant.ORDER_SUBMIT)
	public String submitOrder(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		OrderDTO orderDTO = new OrderDTO();
		
		User user = getCurrentUser();
		
		// 是否需要检查当前用户的位置
		boolean checkLocationByUser = UserUtils.isCheckLocationByUser(user, openids);
		
		if(checkLocationByUser){
			String userLocation = getUserLocation(request);
			
			if(StringUtils.isBlank(userLocation)){
				orderDTO.setMsg(ResponseConstant.ORDER_USER_NO_LOCATION_FAILED);
				orderDTO.setCode(ResponseConstant.NO_USER_LOCSTION);
			}else if("notSupported".equals(userLocation)){
				orderDTO.setMsg(ResponseConstant.ORDER_USER_LOCATION_FAILED);
				orderDTO.setCode(ResponseConstant.NOT_SUPPORT_USER_LOCSTION);
			}else{
				log.info("controller submit order...");
				String sessionId = UserUtils.getSessionId(request, response);
				
				//orderDTO = orderService.submitOrder(user, sessionId);
				
				if(orderDTO == null){
					orderDTO = new OrderDTO();
					orderDTO.setMsg(ResponseConstant.ORDER_FAILED);
					orderDTO.setCode(ResponseConstant.FAILED);
				}
			}
		}else{
			log.info("controller submit order...");
			String sessionId = UserUtils.getSessionId(request, response);
			
			//orderDTO = orderService.submitOrder(user, sessionId);
			
			if(orderDTO == null){
				orderDTO = new OrderDTO();
				orderDTO.setMsg(ResponseConstant.ORDER_FAILED);
				orderDTO.setCode(ResponseConstant.FAILED);
			}
		}
		
		String orderDTOJson = JsonUtils.ObjectAsString(orderDTO);
		log.info("controller submit order end.result:"+orderDTOJson);
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter writer = response.getWriter();
		writer.write(orderDTOJson);
		
		return null;
	}
	
	private String getUserLocation(HttpServletRequest request){
		
		Cookie cookie = CookieUtils.getCookie(request, CommonConstant.USER_LOCATION);
		if(cookie == null){
			log.info("cookie中没有用户的位置信息。");
			return null;
		}
		
		String countryByLatitudeAndLongitude = locationUtils.getCountryByLatitudeAndLongitude(cookie.getValue());
		
		if(StringUtils.isBlank(countryByLatitudeAndLongitude)){
			log.info("所在位置不支持购物");
			return "notSupported";
		}
		
		return countryByLatitudeAndLongitude;
	}
}
